﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KamLib;


namespace Ext.Net.UIS
{

    public class ModelField : Ext.Net.ModelField
    {
        public readonly Term Term;
        public List<string> References = new List<string>();
        public List<string> Dependencies = new List<string>();

        public ModelField(Term term) : base(term.FieldName) { Term = term; }
    }


    public static class ModelHelper
    {

        public static void AddFields(this Ext.Net.Model model, TermNode node, List<Term> terms)
        {
            var fields = new List<ModelField>();
            foreach (var term in terms)
            {
                if (!term.Name.yes()) continue;
                if (term.Have(TermTags.ID))
                    model.IDProperty = term.Name;

                var field = new ModelField(term);
                if (term.CalculateScript != null)
                    field.Convert.Fn = term.CalculateScript.ToScript(node, field);

                fields.Add(field);
            }

            foreach (var field in fields)
            {
                foreach (var reference in field.References)
                {
                    var refField = fields.FirstOrDefault(a => a.Name == reference);
                    if (refField != null)
                        refField.Dependencies.Add(field.Name);
                }

            }

            var sb = new StringBuilder();
            foreach (var field in fields)
            {
                if (field.Dependencies.Count == 0) continue;
                sb.Clear();
                sb.Append('[');
                var isnext = false;
                foreach (var dependency in field.Dependencies)
                {
                    if (isnext) sb.Append(", "); else isnext = true;
                    sb.Append('\'');
                    sb.Append(dependency);
                    sb.Append('\'');
                }
                sb.Append(']');
                field.CustomConfig.Add(new ConfigItem("dependencies", sb.ToString(), ParameterMode.Raw));
            }

            model.Fields.AddRange(fields);
        }

    }

}
